package com.fly.common.init;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.stream.Stream;

import javax.annotation.PostConstruct;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.druid.pool.DruidDataSource;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class DataBaseInit
{
    @Autowired
    JdbcTemplate jdbcTemplate;
    
    @Autowired
    DruidDataSource dataSource;
    
    @PostConstruct
    public void init()
    {
        try
        {
            log.info("dataSource driverClass: {} ", dataSource.getDriverClassName());
            if (org.h2.Driver.class.getName().equals(dataSource.getDriverClassName()))
            {
                Resource resource = new ClassPathResource("sql/init-h2.sql");
                String text = IOUtils.toString(resource.getURL(), StandardCharsets.UTF_8.toString());
                Stream.of(text.split(";")).filter(StringUtils::isNotBlank).forEach(jdbcTemplate::execute);
                return;
            }
            if (com.mysql.jdbc.Driver.class.getName().equals(dataSource.getDriverClassName()))
            {
                Resource resource = new ClassPathResource("sql/init.sql");
                String text = IOUtils.toString(resource.getURL(), StandardCharsets.UTF_8.toString());
                Stream.of(text.split(";")).filter(StringUtils::isNotBlank).forEach(jdbcTemplate::execute);
                return;
            }
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
        }
    }
}
